<template>
  <div class="calendar">
    <div class="calendar-header">
      <el-select v-model="selectedYear" size="small" style="width: 100px;margin-right: 10px;" @change="onYearMonthChange">
        <el-option
          v-for="year in years"
          :key="year"
          :label="year + '年'"
          :value="year"
        />
      </el-select>
      <el-select v-model="selectedMonth" size="small" style="width: 90px;" @change="onYearMonthChange">
        <el-option
          v-for="(m, i) in 12"
          :key="i"
          :label="(i + 1) + '月'"
          :value="i + 1"
        />
      </el-select>
    </div>

    <div class="grid grid-cols-7 gap-2">
      <div v-for="day in weekDays" :key="day" class="day-name">{{ day }}</div>
      <div
        v-for="(day, index) in monthDays"
        :key="index"
        class="day-cell"
        :class="{ 'grayed': day.notCurrentMonth }"
      >
        <div>
          <div class="date-number">{{ day.date.date() }}</div>
          <div class="shifts" v-if="!day.empty && !day.notCurrentMonth">
            <div class="shift">
              <div><span class="dot" :class="day.details?.firstTeam?'ypb':'wpb'"></span>早班</div><el-icon v-if="useInfo.deptAdmin" class="edit" @click="editClick(day, 'firstTeam')"><Edit /></el-icon>
            </div>
            <div class="shift">
              <div><span class="dot" :class="day.details?.secondTeam?'ypb':'wpb'"></span>午班</div><el-icon v-if="useInfo.deptAdmin"  class="edit" @click="editClick(day, 'secondTeam')"><Edit /></el-icon>
            </div>
            <div class="shift">
              <div><span class="dot" :class="day.details?.thirdTeam?'ypb':'wpb'"></span>晚班</div><el-icon v-if="useInfo.deptAdmin"  class="edit" @click="editClick(day, 'thirdTeam')"><Edit /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible.visible" title="选择值班人员" width="500" :close-on-click-modal="false">
      <el-form :model="dialogVisible.form" :rules="dialogVisible.rules" ref="dialogVisibleFormRef" label-position="top">
        <el-form-item label="人员" prop="responsibleBy" style="margin-bottom: 5px">
          <el-tree-select
            v-model="dialogVisible.form.responsibleBy"
            :data="dialogVisible.responseOptions"
            :render-after-expand="false"
            show-checkbox
            :props="dialogVisible.treeProps"
            check-on-click-node
            node-key='id'
            filterable
            multiple
            style="width: 100%"
            placeholder="请选择人员"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible.visible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import dayjs from 'dayjs'
import { ref, defineProps, defineExpose } from 'vue'
import { deptSonUserTree } from "@/api/system/role"
import { detailList, putDetail } from "@/api/system/setting"
import useUserStore from "@/store/modules/user"

const proxy = defineProps({
  form: {
    type: Object,
    required: true
  }
})

const today = dayjs()
const selectedYear = ref(today.year())
const selectedMonth = ref(today.month() + 1) // dayjs月份从0开始
const useInfo = ref({}) // 是否有权限编辑
const currentMonth = ref(dayjs(`${selectedYear.value}-${selectedMonth.value}-01`))

const years = Array.from({ length: 10 }, (_, i) => today.year() - 5 + i)

const monthDays = ref([])

const updateMonthDays = () => {
  const startOfMonth = currentMonth.value.startOf('month')
  const startDay = startOfMonth.day()
  const daysInMonth = currentMonth.value.daysInMonth()
  const totalCells = Math.ceil((startDay + daysInMonth) / 7) * 7

  const days = []
  const prevMonth = currentMonth.value.subtract(1, 'month')
  const nextMonth = currentMonth.value.add(1, 'month')
  const daysInPrevMonth = prevMonth.daysInMonth()

  // 上月末尾几天
  for (let i = startDay - 1; i >= 0; i--) {
    const date = prevMonth.date(daysInPrevMonth - i)
    days.push({ date, notCurrentMonth: true, empty: false, details:{}})
  }

  // 当前月
  for (let d = 1; d <= daysInMonth; d++) {
    const date = currentMonth.value.date(d)
    days.push({ date, notCurrentMonth: false, empty: false, details:{}})
  }

  // 下月补齐
  const remaining = totalCells - days.length
  for (let d = 1; d <= remaining; d++) {
    const date = nextMonth.date(d)
    days.push({ date, notCurrentMonth: true, empty: false, details:{}})
  }

  monthDays.value = days
}

function onYearMonthChange() {
  currentMonth.value = dayjs(`${selectedYear.value}-${selectedMonth.value}-01`)
  updateMonthDays() // 更新日历天数
  getDetailList() // 获取数据并映射
}

const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

const dayItem = ref({
  day: {},
  item: ''
})
// 选择值班
const editClick = (day, item) => {
  const date = day.date.format('YYYY-MM-DD')
  console.log(`Edit shift for ${date}`)
  dayItem.value.day = day
  dayItem.value.item = item
  // 在这里可以添加逻辑来处理值班编辑
  dialogVisibleFormRef?.value?.resetFields()
  let responsibleBy = day.details[item] ? day.details[item].split(',') : [] // 选中值班人员
  dialogVisible.form.responsibleBy = responsibleBy.map((item) => Number(item))
  console.log(dialogVisible.form.responsibleBy);
  
  dialogVisible.visible = true
}

const dialogVisibleFormRef = ref(null)
const dialogVisible = reactive({
  visible: false,
  form: {
    responsibleBy: []
  },
  rules: {
    responsibleBy: [{ required: true, message: '请选择人员', trigger: 'change' }]
  },
  responseOptions: [],
  treeProps: {
  value: 'id',
  label: 'label',
  children: 'children',
  // 可选：禁用用户节点选择
  disabled: (data) => !data.isUser
  }
})

useUserStore().getInfo().then((res)=>{
  useInfo.value = res.user
  deptSonUserTree({deptId:res.user.dept.deptId}).then((response) => {
    if(response.code == 200) {
      dialogVisible.responseOptions  = [transformDeptTree(response.data,true)];
    }
  })
})

const submitHandle = () => {
  const form = dialogVisible.form
  dialogVisibleFormRef.value.validate((valid) => {
    if (valid) {
      let data = {
        ...proxy.form,
        scheduleDetailId: dayItem.value.day.details.scheduleDetailId,
        applyDate: dayItem.value.day.date.format('YYYY-MM-DD'),
      }
      data[dayItem.value.item] = form.responsibleBy.join()
      // 在这里可以添加逻辑来处理提交的数据
      putDetail(data).then((response) => {
        if (response.code == 200) {
          getDetailList()
          dialogVisible.visible = false
        }
      })
    } else {
      return false
    }
  })
}

const getDetailList = () => {
  const startDate = dayjs(`${selectedYear.value}-${selectedMonth.value}-01`).startOf('month').format('YYYY-MM-DD')
  const endDate = dayjs(`${selectedYear.value}-${selectedMonth.value}-01`).endOf('month').format('YYYY-MM-DD')
  detailList({ applyStartDate: startDate, applyEndDate: endDate }).then((response) => {
    if (response.code == 200) {
      // 遍历返回的数据，将 applyDate 映射到 monthDays
      response.rows.forEach((item) => {
        const applyDate = dayjs(item.applyDate).format('YYYY-MM-DD')
        const day = monthDays.value.find((d) => d.date.format('YYYY-MM-DD') === applyDate)
        if (day && !day.notCurrentMonth) {
          day.details = item // 将数据存入对应日期
        }
      })
    }
  })
}

function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => {
        if(useInfo.value.userId == user.userId) {
          useInfo.value.deptAdmin = user.deptAdmin
        }
       return {
        id: user.userId,
        name: user.userName,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }})
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}

const init = () => {
  updateMonthDays()
  getDetailList()
}

defineExpose({
  init
})
</script>

<script>
export default {
  name: 'ShiftCalendar'
}
</script>

<style scoped>
.calendar {
  padding: 20px;
}
.calendar-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  justify-content: flex-end;
}
.day-name {
  font-weight: bold;
  text-align: center;
}
.day-cell {
  border: 1px solid #eee;
  min-height: 100px;
  padding: 4px;
  font-size: 12px;
}
.date-number {
  font-weight: bold;
  margin-bottom: 4px;
}
.shifts {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.shift {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: space-between;
  padding-right: 10px;
}
.shift>div{
  display: flex;
  align-items: center;
}
.dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 5px;
}
.wpb {
  background-color: #bfcbd9;
}
.ypb {
  background-color: #19be6b;
}
.grayed {
  color: #ccc;
  background-color: #f9f9f9;
}
.edit{
  cursor: pointer;
  display: none;
}
.shift:hover{
  background-color: #bfcbd93d;
}
.shift:hover .edit{
  display: inline-block;
}
</style>
